package com.life.ai.server;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import com.baomidou.mybatisplus.generator.fill.Column;
import org.apache.ibatis.annotations.Mapper;

import java.util.Collections;

import static com.life.ai.server.CodeGenerator.GeneratorConfig.*;

/**
 * mybatis-plus代码生成器
 */
public class CodeGenerator {

    public static void main(String[] args) {
        // 执行代码生成
        GeneratorConfig.packageName("com.life.ai.server.modules");
        GeneratorConfig.moduleName("life");
        GeneratorConfig.author("yukky");
        GeneratorConfig.tables("");
        GeneratorConfig.tablesPrefix("");
        GeneratorConfig.enableController(true);
        startGenerate();
    }

    static class GeneratorConfig {
        /**
         * 项目路径
         */
        public static final String PROJECT_PATH = System.getProperty("user.dir");

        /**
         * 生成参数配置
         */
        public static boolean controller = true;
        public static       String   AUTHOR        = "yukky";
        public static       String   PACKAGE_NAME  = "com.demo";
        public static       String   MODULE_NAME   = "";
        public static       String[] TABLES        = {};
        public static       String[] TABLES_PREFIX = {};
        /**
         * 数据库连接字段配置
         */
        public static final String   JDBC_URL      = "jdbc:mysql://127.0.0.1:3306/ai_server?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false";
        public static final String   JDBC_USERNAME = "root";
        public static final String   JDBC_PASSWORD = "123456";


        public static final String LOGIC_DELETE = "is_deleted";  // 逻辑删除

        public static final String CREATE_BY   = "create_by";    // 创建人
        public static final String CREATE_TIME = "create_time";  // 创建时间

        public static final String UPDATE_BY   = "update_by";    // 更新人
        public static final String UPDATE_TIME = "update_time";  // 更新时间


        public static void enableController(boolean enableController) {
            controller = enableController;
        }

        public static void author(String author) {
            AUTHOR = author;
        }

        public static void packageName(String packageName) {
            PACKAGE_NAME = packageName;
        }

        public static void moduleName(String moduleName) {
            MODULE_NAME = moduleName;
        }

        public static void tables(String... tables) {
            TABLES = tables;
        }

        public static void tablesPrefix(String... tablesPrefix) {
            TABLES_PREFIX = tablesPrefix;
        }
    }

    public static void startGenerate() {
        FastAutoGenerator fastAutoGenerator = FastAutoGenerator.create(new DataSourceConfig.Builder(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD));
        fastAutoGenerator.strategyConfig(builder -> {
            builder.addInclude(TABLES) // 设置需要生成的表名
                    .addTablePrefix(TABLES_PREFIX); // 设置过滤表前缀
        });
        setGlobalConfig(fastAutoGenerator);     // 全局配置
        setPackageConfig(fastAutoGenerator);    // 包配置
        setEntityConfig(fastAutoGenerator);     // Entity配置
        setServiceConfig(fastAutoGenerator);    // Service配置
        setMapperConfig(fastAutoGenerator);     // Mapper配置
        setControllerConfig(fastAutoGenerator); // Xml配置
        setTemplateConfig(fastAutoGenerator);   // 模板配置
        fastAutoGenerator.execute();            // 执行代码生成
    }

    /**
     * 全局配置
     */
    private static void setGlobalConfig(FastAutoGenerator fastAutoGenerator) {
        fastAutoGenerator.globalConfig(builder -> {
            builder.author(AUTHOR)// 设置作者
                    .disableOpenDir()
                    .outputDir(PROJECT_PATH + "/src/main/java") // 指定输出目录
                    .dateType(DateType.ONLY_DATE)
                    .commentDate("yyyy-MM-dd");   // 注释日期
            builder.enableSwagger(); // 开启 swagger 模式
        });
    }

    /**
     * 包配置
     */
    private static void setPackageConfig(FastAutoGenerator fastAutoGenerator) {
        StringBuilder packagePath = new StringBuilder(PACKAGE_NAME);
        StringBuilder mapperPath = new StringBuilder(PROJECT_PATH).append("/src/main/resources/mapper");
        if (StringUtils.isNotBlank(MODULE_NAME)) {
            packagePath.append(".").append(MODULE_NAME);
            mapperPath.append("/").append(MODULE_NAME);
        }
        fastAutoGenerator.packageConfig(builder -> {
            builder.parent(packagePath.toString())    // 设置父包名
                    // 自定义Xml生成路径
                    .pathInfo(Collections.singletonMap(OutputFile.xml, mapperPath.toString()));
        });
    }

    /**
     * 实体类 Entity 配置
     */
    private static void setEntityConfig(FastAutoGenerator fastAutoGenerator) {
        fastAutoGenerator.strategyConfig(builder -> {
            builder.entityBuilder()
                    .naming(NamingStrategy.underline_to_camel)          //表名下划线转驼峰
                    .columnNaming(NamingStrategy.underline_to_camel)    //字段下划线转驼峰
                    .idType(IdType.ASSIGN_ID)                           //雪花id
                    .logicDeleteColumnName(LOGIC_DELETE)                //逻辑删除字段名
                    //自动填充配置
                    .addTableFills(new Column(CREATE_BY, FieldFill.INSERT))
                    .addTableFills(new Column(CREATE_TIME, FieldFill.INSERT))
                    .addTableFills(new Column(UPDATE_BY, FieldFill.INSERT_UPDATE))
                    .addTableFills(new Column(UPDATE_TIME, FieldFill.INSERT_UPDATE))
                    .enableTableFieldAnnotation()                       //开启生成实体时生成字段注解
                    .enableChainModel()                                 // 开启链式编程
                    .enableLombok();                                    // 开启lombok
        });
    }

    /**
     * 业务层 Service 配置
     */
    private static void setServiceConfig(FastAutoGenerator fastAutoGenerator) {
        fastAutoGenerator.strategyConfig(builder -> {
            builder.serviceBuilder()
                    .formatServiceFileName("%sService")             // 格式化 service 接口文件名称
                    .formatServiceImplFileName("%sServiceImpl");    // 格式化 service 实现类文件名称
        });
    }

    /**
     * 业务层 Mapper 配置
     */
    private static void setMapperConfig(FastAutoGenerator fastAutoGenerator) {
        fastAutoGenerator.strategyConfig(builder -> {
            builder.mapperBuilder()
                    .mapperAnnotation(Mapper.class)
                    .formatMapperFileName("%sMapper") // 格式化 mapper 文件名称
                    .formatXmlFileName("%sMapper");   // 格式化 xml 实现类文件名称
        });
    }

    /**
     * 业务层 Controller 配置
     */
    private static void setControllerConfig(FastAutoGenerator fastAutoGenerator) {
        fastAutoGenerator.strategyConfig(builder -> {
            builder.controllerBuilder()
                    .formatFileName("%sController")     //格式化文件名称
                    .enableRestStyle()                  // 开启 @RestController
                    .build();
        });
    }

    /**
     * 模板配置
     */
    private static void setTemplateConfig(FastAutoGenerator fastAutoGenerator) {
        fastAutoGenerator.templateEngine(new VelocityTemplateEngine());
        fastAutoGenerator.templateConfig(builder -> {
            builder.controller(controller ? "/vm/controller.java.vm" : "");
            builder.service("/vm/service.java.vm");
            builder.serviceImpl("/vm/serviceImpl.java.vm");
        });
    }
}